package cn.kivensoft.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/** 多个值同键名的map
 * @author kiven lee
 * @version 1.0
 * @since 2020-12-28
 */
public class MultiMap<K, V> extends HashMap<K, List<V>> {
	private static final long serialVersionUID = 1L;

	public void putValue(K key, V value) {
		List<V> list = get(key);
		if (list == null) {
			list = new ArrayList<>();
			put(key, list);
		}
		list.add(value);
	}
	
	public V getFirst(K key) {
		List<V> list = get(key);
		return (list == null || list.isEmpty()) ? null : list.get(0);
	}

	public boolean removeValue(K key, V value) {
		boolean finded = false;
		List<V> list = get(key);
		if (list != null) {
			Iterator<V> iter = list.iterator();
			while (iter.hasNext()) {
				if (value.equals(iter.next())) {
					iter.remove();
					finded = true;
					break;
				}
			}
			if (finded && list.isEmpty())
				remove(key);
		}
		return finded;
	}

}
